package com.xhwl.logistics.strategy.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.cent.sdata.Project;
import com.xhwl.common.vo.cent.vehicle.CarVO;
import com.xhwl.logistics.bo.VehicleCarportBO;
import com.xhwl.logistics.bo.cent.VehicleIntegratedConfigBO;
import com.xhwl.logistics.bo.input.QueryVehicleCarportBO;
import com.xhwl.logistics.bo.manipulate.VehicleSyncBO;
import com.xhwl.logistics.converter.mapstruct.VehicleAreaThirdConverter;
import com.xhwl.logistics.converter.mapstruct.VehicleCarportUseInfoThirdConverter;
import com.xhwl.logistics.converter.mapstruct.VehicleParkingLotThirdConverter;
import com.xhwl.logistics.converter.mapstruct.VehiclePassageThirdConverter;
import com.xhwl.logistics.dto.http.CarportChuangXiangDTO;
import com.xhwl.logistics.dto.http.ParkingLotInfoChuangXiangDTO;
import com.xhwl.logistics.dto.http.ParkingLotPassageChuangXiangDTO;
import com.xhwl.logistics.dto.query.DeviceControlDTO;
import com.xhwl.logistics.entity.VehicleArea;
import com.xhwl.logistics.entity.VehicleParkingLot;
import com.xhwl.logistics.entity.VehiclePassage;
import com.xhwl.logistics.service.business.VehicleCommonBusinessService;
import com.xhwl.logistics.service.impl.VehicleAreaServiceImpl;
import com.xhwl.logistics.service.impl.VehicleParkingLotServiceImpl;
import com.xhwl.logistics.service.impl.VehiclePassageServiceImpl;
import com.xhwl.logistics.service.impl.http.ChuangXiangHttpServiceImpl;
import com.xhwl.logistics.strategy.IVehicleParkingLotHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 对接创享同步基本信息
 */
@Slf4j
//@Service
public class VehicleParkingLotChuangXiangHandlerImpl implements IVehicleParkingLotHandler {

    @Autowired
    private ChuangXiangHttpServiceImpl chuangXiangHttpService;

    @Autowired
    private VehicleCommonBusinessService vehicleCommonBusinessService;

    @Autowired
    private VehicleParkingLotServiceImpl vehicleParkingLotService;

    @Autowired
    private VehicleParkingLotThirdConverter vehicleParkingLotThirdConverter;

    @Autowired
    private VehicleAreaThirdConverter vehicleAreaThirdConverter;

    @Autowired
    private VehicleAreaServiceImpl vehicleAreaService;

    @Autowired
    private VehiclePassageThirdConverter vehiclePassageThirdConverter;

    @Autowired
    private VehiclePassageServiceImpl vehiclePassageService;

    @Autowired
    private VehicleCarportUseInfoThirdConverter vehicleCarportUseInfoThirdConverter;

    //常量
    private static final Integer openDevice = 1;
    private static final Integer closeDevice = 0;
    private static final String carType = "访客车型";

    /**
     * 同步车场基本信息
     * @param vehicleIntegratedConfigBO
     * @param vehicleSyncBO
     */
    @Override
    public void sync(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, VehicleSyncBO vehicleSyncBO) {
        log.info("ChuangXiang sync start!");
        //同步车场信息
        Project project = vehicleCommonBusinessService.getProjectById(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
        if(project==null){
            return;
        }
        ParkingLotInfoChuangXiangDTO parkingLotInfoFromChuangXiang = chuangXiangHttpService.getParkingLotInfo(vehicleIntegratedConfigBO);
        List<VehicleParkingLot> vehicleParkingLotListFromThird = new LinkedList<>();

        if(parkingLotInfoFromChuangXiang!=null){
            VehicleParkingLot vehicleParkingLot = vehicleParkingLotThirdConverter.
                    chuangXiangtoVehicleParkingLot(parkingLotInfoFromChuangXiang, project.getId());

            vehicleParkingLotListFromThird.add(vehicleParkingLot);
        }
        List<VehicleParkingLot> vehicleParkingLotListFromCent = vehicleParkingLotService.list(new LambdaQueryWrapper<VehicleParkingLot>().eq(VehicleParkingLot::getProjectId,
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId()).eq(
                        VehicleParkingLot::getParkId,vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getParkId()
        ));

        vehicleCommonBusinessService.syncParkingLot(vehicleParkingLotListFromCent,vehicleParkingLotListFromThird);

        //同步区域信息，由于创享没有区域的概念，所以虚拟一个区域信息
        List<VehicleArea> vehicleAreaListFromThird = new LinkedList<>();

        if (parkingLotInfoFromChuangXiang != null) {
            VehicleParkingLot vehicleParkingLot = vehicleParkingLotService.getOne(new LambdaQueryWrapper<VehicleParkingLot>().eq(
                    VehicleParkingLot::getParkId, parkingLotInfoFromChuangXiang.getParkingId()
                    ).eq(
                    VehicleParkingLot::getProjectId,vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId())
            );
            if(vehicleParkingLot==null){
                throw new BusinessException("创享，第三方车场id变动了，请重新点击同步按钮！");
            }
            VehicleArea vehicleArea = vehicleAreaThirdConverter.
                    chuangXiangtoVehicleArea(parkingLotInfoFromChuangXiang, vehicleParkingLot.getId());

            vehicleAreaListFromThird.add(vehicleArea);
        }
        List<VehicleParkingLot> vehicleParkingLotList = vehicleParkingLotService.list(new LambdaQueryWrapper<VehicleParkingLot>().eq(VehicleParkingLot::getProjectId,
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId()).eq(
                        VehicleParkingLot::getParkId,vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getParkId()
        ));
        List<Integer> parkingLotIds = vehicleParkingLotList.stream().map(s -> s.getId()).collect(Collectors.toList());
        List<VehicleArea> vehicleAreaListFromCent = vehicleAreaService.list(new LambdaQueryWrapper<VehicleArea>().in(
                VehicleArea::getParkingLotId,parkingLotIds
        ));

        vehicleCommonBusinessService.syncArea(vehicleAreaListFromCent,vehicleAreaListFromThird);

        //同步通道信息
        List<ParkingLotPassageChuangXiangDTO> passageInfoFromChuangXiang = chuangXiangHttpService.getPassageInfo(vehicleIntegratedConfigBO);
        List<VehiclePassage> vehiclePassageListFromThird = new LinkedList<>();
        VehicleParkingLot vehicleParkingLot = null;

        if(!passageInfoFromChuangXiang.isEmpty()){
            if(parkingLotInfoFromChuangXiang!=null){
                vehicleParkingLot = vehicleParkingLotService.getOne(new LambdaQueryWrapper<VehicleParkingLot>().eq(
                        VehicleParkingLot::getParkId, parkingLotInfoFromChuangXiang.getParkingId()
                        ).eq(
                        VehicleParkingLot::getProjectId,vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId())
                );
                if(vehicleParkingLot==null){
                    throw new BusinessException("创享，第三方车场id变动了，请重新点击同步按钮！");
                }
                VehicleArea vehicleArea = vehicleAreaService.getOne(new LambdaQueryWrapper<VehicleArea>().eq(
                        VehicleArea::getParkingLotId, vehicleParkingLot.getId()
                ));
                if(vehicleArea==null){
                    throw new BusinessException("创享，通过车场id未找到区域id");
                }
                for (ParkingLotPassageChuangXiangDTO parkingLotPassageChuangXiangDTO : passageInfoFromChuangXiang) {
                    VehiclePassage vehiclePassage = vehiclePassageThirdConverter.chuangXiangtoVehiclePassage(parkingLotPassageChuangXiangDTO, project.getId(),
                            vehicleParkingLot.getId(), vehicleArea.getId());
                    vehiclePassageListFromThird.add(vehiclePassage);
                }
            }
        }

        List<VehiclePassage> vehiclePassageListFromCent = vehiclePassageService.list(new LambdaQueryWrapper<VehiclePassage>().eq(
                VehiclePassage::getProjectId, project.getId()
        ).eq(
                Objects.nonNull(vehicleParkingLot),VehiclePassage::getParkingLotId,vehicleParkingLot.getId()
        ));

        vehicleCommonBusinessService.syncPassage(vehiclePassageListFromCent,vehiclePassageListFromThird);
        log.info("ChuangXiang sync end!");
    }

    @Override
    public VehicleCarportBO queryCarport(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, QueryVehicleCarportBO queryVehicleCarportBO) {
        CarportChuangXiangDTO parkingCarspotInfo = chuangXiangHttpService.getParkingCarspotInfo(vehicleIntegratedConfigBO);
        return vehicleCarportUseInfoThirdConverter.chuangXiangtoVehicleCarportBO(parkingCarspotInfo);
    }

    @Override
    public void openDevice(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, DeviceControlDTO deviceControlDTO) {
        if(deviceControlDTO.getId() == null){
            throw new BusinessException("通道id为空！");
        }
        VehiclePassage vehiclePassage = vehiclePassageService.getById(deviceControlDTO.getId());
        if(vehiclePassage == null){
            throw new BusinessException("通过该通道id未找到通道信息!");
        }
        JSONArray deviceStatusInfo = chuangXiangHttpService.getDeviceStatusInfo(vehicleIntegratedConfigBO);
        if(deviceStatusInfo.isEmpty()){
            throw new BusinessException("该道闸为虚拟设备无法进行控制！");
        }
        chuangXiangHttpService.controlDevice(vehicleIntegratedConfigBO, vehiclePassage.getThirdPassageId(), openDevice);
    }

    @Override
    public void closeDevice(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, DeviceControlDTO deviceControlDTO) {
        if(deviceControlDTO.getId() == null){
            throw new BusinessException("通道id为空！");
        }
        VehiclePassage vehiclePassage = vehiclePassageService.getById(deviceControlDTO.getId());
        if(vehiclePassage == null){
            throw new BusinessException("通过该通道id未找到通道信息!");
        }
        JSONArray deviceStatusInfo = chuangXiangHttpService.getDeviceStatusInfo(vehicleIntegratedConfigBO);
        if(deviceStatusInfo.isEmpty()){
            throw new BusinessException("该道闸为虚拟设备无法进行控制！");
        }
        chuangXiangHttpService.controlDevice(vehicleIntegratedConfigBO, vehiclePassage.getThirdPassageId(), closeDevice);
    }

    @Override
    public String reserverSpace(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, CarVO carVO) {
        try{
            chuangXiangHttpService.reserveCar(vehicleIntegratedConfigBO, carVO, getChuangXiangCarModelId(vehicleIntegratedConfigBO));
        }catch (Exception e){
            throw new DataException("预约失败");
        }
        return "";
    }

    /**
     * 获取创享指定车的车型id
     */
    private String getChuangXiangCarModelId(VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        JSONArray carTypeInfo = chuangXiangHttpService.getCarTypeInfo(vehicleIntegratedConfigBO);
        List<JSONObject> carTypes = carTypeInfo.stream().map(o -> (JSONObject) o)
                .filter(s -> StringUtils.equals(s.getString("carmodelName"), carType))
                .collect(Collectors.toList());
        if(carTypes.isEmpty()){
            throw new BusinessException("创享的车型接口有变化，请联系开发人员");
        }
        return carTypes.get(0).getString("carmodelId");
    }
}
